#include "Node.h"
#include <QObject>
#include <QtGui>
#include "Editor.h"
#include "SceneView.h"

Scene* Node::scene;

static void updateView() {
	((SceneView*)Editor::ins().centralWidget())->viewport()->update();
}

Node::Node()
	: m_pParent(NULL)
	, name(QObject::tr("unnamed"))
	, m_X(0.0f), m_Y(0.0f)
	, m_ScaleX(1.0f), m_ScaleY(1.0f)
	, m_Selected(false)
{
}

Node::~Node(void)
{
	foreach(Node* ch, children)
		delete ch;
}

void Node::addChild(Node* node)  {
	children.append(node);
	node->m_pParent = this;
	scene->notifyNodeChange(node);
}

void Node::addChildAt(Node* node, int pos) {
	children.insert(pos, node);
	node->m_pParent = this;
	scene->notifyNodeChange(node);
}

bool Node::removeChild(Node* node) {
	if (children.removeOne(node)) {
		node->m_pParent = 0;
		return true;
	}
	return false;
}

void Node::setPos(float x, float y) {
	m_X = x;
	m_Y = y;
	updateView();
}

void Node::setX(float x) {
	m_X = x;
	updateView();
}
void Node::setY(float y) {
	m_Y = y;
	updateView();
}

void Node::setScaleX(float sx) {
	m_ScaleX = sx;
	updateView();
}

void Node::setScaleY(float sy) {
	m_ScaleY = sy;
	updateView();
}

QString Node::typeName() const {
	switch(type()) {
	case NNode:
		return "empty";
	case NSprite:
		return "sprite";
	case NLayer:
		return "layer";
	default:
		return "unrecognized";
	}
}

QTransform Node::transform() const {
	QTransform t;
	t.translate(x(), y());
	t.scale(m_ScaleX, m_ScaleY);
	return t;
}

QTransform Node::worldToNodeTransform() const {
	if (m_pParent) {
		return transform().inverted() * m_pParent->worldToNodeTransform();
	}
	return transform().inverted();
}

void Node::setSelected(bool sel)
{
	if (m_Selected == sel) return;
	m_Selected = sel;
	updateView();
}

void Node::paint(QPainter& painter) {
}

bool Node::contains(const QPointF& point) const {
	return false;
}

QRectF Node::boundingRect() const {
	return QRectF(0, 0, 0, 0);
}

SpriteNode::SpriteNode() : Node() {
}

void SpriteNode::paint(QPainter& painter) {
	painter.drawPixmap(QPoint(0, 0), SpriteNode::defaultImage());
}

bool SpriteNode::contains(const QPointF& point) const {

	QPointF p = point * this->worldToNodeTransform();
	return p.x() > 0 && p.y() > 0 && p.x() < defaultImage().width() && p.y() < defaultImage().height();
}

QPixmap& SpriteNode::defaultImage() {
	static QPixmap map("DefaultSprite.png");
	return map;
}

QRectF SpriteNode::boundingRect() const {
	return QRectF(QPointF(0, 0), defaultImage().size());
}
LayerNode::LayerNode() : Node() {

}

void LayerNode::paint(QPainter& painter) {
}
